package com.hzlj.position.open.api.config;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.fz.common.base.exception.PubException;
import com.google.common.collect.Maps;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Map;

/**
 * @author lifh
 * @date 2022/2/27 16:47
 **/
@Data
@Configuration
@ConfigurationProperties("position.open.api")
public class OpenApiPositionConfig {
    private Map<String, Config> config = Maps.newHashMap();

    @Data
    public static class Config {
        private String key;
        private long timestampDiff = 10 * 60;
    }

    public Config config(String appId) {
        Config config = this.config.get(appId);
        if (ObjectUtil.isEmpty(config)) {
            throw new PubException("未配置该appId，请确认appId是否正确！");
        }
        return config;
    }

    public String key(String appId) {
        Config config = config(appId);
        if (ObjectUtil.isEmpty(config.key)) {
            throw new PubException("未配置key，请确认appId是否正确！");
        }
        return config.key;
    }

    public long timestampDiff(String appId) {
        return config(appId).timestampDiff;
    }

    /**
     * sign=MD5Hex(appId|timestamp|key).toUpperCase()
     */
    public void checkSign(String appId,
                          String timestamp,
                          String sign) {
        if (ObjectUtil.hasEmpty(appId, timestamp, sign)) {
            throw new PubException("请检查header是否正确传入!");
        }
        //校验时间是否匹配
        Date date = new Date(Long.parseLong(timestamp));
        if (DateUtil.between(date, new Date(), DateUnit.SECOND, true) > timestampDiff(appId)) {
            throw new PubException("sign超过有效期，请重新生成！");
        }
        String key = this.key(appId);
        String compareSign = MD5.create().digestHex(appId + "|" + timestamp + "|" + key).toUpperCase();
        if (!compareSign.equals(sign)) {
            throw new PubException("sign不正确！");
        }
    }
}
